package org.atlantis.sbe.functional

/**
 * n：分子，d：分母
 */
class Rational(val n: Int, val d: Int) {
    require(d != 0, "Denominator must be nonzero")

    def this(n: Int) {
        this(n, 1)
    }

    override def toString(): String = {
        if (n % d == 0) return "" + n / d
        n + "/" + d
    }

    def +(other: Rational): Rational = {
        val _n = n * other.d + other.n * d
        val _d = d * other.d
        val gcd = this.gcd(_n, _d)
        new Rational(_n / gcd, _d / gcd)
    }

    def <(other: Rational): Boolean = {
        n * other.d < d * other.n
    }

    def >(other: Rational): Boolean = {
        !(<(other))
    }

    private def gcd(a: Int, b: Int): Int = {
        var _k = 0
        var _a = a
        var _b = b
        do {
            _k = _a % _b
            _a = _b
            _b = _k
        } while (_k != 0)
        _a;
    }
}